package com.zhong.gang.pda.ui.action.deliver.controller;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.luck.picture.lib.tools.ToastUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhong.gang.applib.http.BaseDataBean;
import com.zhong.gang.applib.http.callback.DataCallBack;
import com.zhong.gang.applib.rx.RxManager;
import com.zhong.gang.pda.db.loction.LocationMessageUtils;
import com.zhong.gang.pda.ui.carorder.CarOrderAct;
import com.zhong.gang.pda.api.Api;
import com.zhong.gang.applib.config.Config;
import com.zhong.gang.pda.db.user.UserBean;
import com.zhong.gang.pda.db.user.UserUtils;
import com.zhong.gang.pda.mvp.CommonPresenter;
import com.zhong.gang.pda.R;
import com.zhong.gang.pda.ui.carorder.OrderListener;
import com.zhong.gang.pda.ui.carorder.OrderNumBean;
import com.zhong.gang.applib.ui.chese.MaterialTypeBean;
import com.zhong.gang.pda.ui.action.HuoBean;
import com.zhong.gang.pda.ui.action.deliver.DeliverAct;
import com.zhong.gang.applib.ui.chese.MaterialAct;
import com.zhong.gang.applib.CheseListener;
import com.zhong.gang.applib.ui.view.ViewClickedListener;
import com.zhong.gang.pda.ui.main.MainBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static android.app.Activity.RESULT_OK;

public class DeliverActionController extends BaseDeliverController
        implements OrderListener, CheseListener , ViewClickedListener {
    private MaterialTypeBean materialTypeBean;
    private DeliverUpDataPersenter persenter;

    public DeliverActionController(DeliverAct act,int id) {
        super(act,id);
        bind.sendCardView.showEdt(true);
        bind.sendCardView.setListener(this::onViewClicked);
        bind.daohuocailiao.setEnabled(true);
        bind.sure.setVisibility(View.VISIBLE);
        persenter = new DeliverUpDataPersenter();
        act.showMainFragemt();
    }

    @Override
    public void setScalesMsg(HuoBean data) {
        super.setScalesMsg(data);
        if (data.getOrderSend() != null){
            bind.sendCardView.setData(data.getOrderSend().getOrderSendDispatchingCar());
            if (bind.sendCardView.getBean() != null && bind.sendCardView.getBean().getType() == 1) {
                bind.daohuocailiao.setVisibility(View.VISIBLE);
            }else {
                bind.daohuocailiao.setVisibility(View.GONE);
            }
            bind.sendSn.setText(data.getOrderSend().getSn());
            bind.daohuoType.setText(data.getOrderSend().getSteelMillMaterialTypeStr());
            for (int n = 0 ;n < data.getOrderSend().getOrderMaterialTypeDetailList().size();n++){
                HuoBean.OrderMaterialTypeDetailBean bean = data.getOrderSend().getOrderMaterialTypeDetailList().get(n);
                bind.fahuo.addView(bean);
            }
            String[] allStrs = data.getOrderSend().getFullPhoto().split(",");
            for (String str : allStrs){
                imgController.addImgView(allAdapter,str);
            }
        }else {
            bind.fahuo.addView();
        }
        if (TextUtils.isEmpty(huoBean.getSecondTime())){
            setEnabled(true);
        }else {
            setEnabled(data.getOrderSend() == null || !data.getOrderSend().getFullPhoto().startsWith("http"));
        }
    }

    private void setEnabled(boolean status){
        bind.daohuocailiao.setEnabled(status);
        bind.sendCardView.showEdt(status);
        bind.fahuo.setEnabled(status);
        bind.sure.setVisibility(status? View.VISIBLE:View.GONE);
        imgController.setNeedImg(allAdapter,act,status,Config.ALL_CLICKED,status);
        bind.sure.setVisibility(status? View.VISIBLE:View.GONE);
    }

    /**
     * 点击事件
     * @param view
     */
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.daohuocailiao://料型
                UserBean userBean = UserUtils.getIntent(act).getUser();
                MaterialAct.openAct(act, Api.getMaterialType,
                        bind.sendCardView.getBean().getEndLocalId()+"",1+""
                        ,userBean.isLogin(),userBean.getToken(),userBean.getId()+"",userBean.getRoleId()+"",this);
                break;
            case R.id.sure://确定
                if (bind.sendCardView.getBean() == null){
                    ToastUtils.s(act,"请选择派车信息");
                    return;
                }
                if (materialTypeBean == null && bind.sendCardView.getBean().getType() == 1){
                    ToastUtils.s(act,"请选择到货料型");
                    return;
                }
                String weightStr = bind.fahuo.getJsonArray();
                if (TextUtils.isEmpty(weightStr)){
                    ToastUtils.s(act,"请选择料型类型");
                    return;
                }
                File allFile = imgController.getFile(allAdapter);
                if (allFile == null){
                    ToastUtils.s(act,"请选择满仓照片");
                    return;
                }
                saveData(weightStr,allFile.toString());
                break;
        }
    }



    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK || data == null)
            return;
        if (requestCode == Config.ALL_CLICKED || requestCode == Config.HALF_CLICKED) {
            imgController.onActivityResult( allAdapter,resultCode,data);
        }else if(requestCode == Config.SCAN){
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                String result = bundle.getString(CodeUtils.RESULT_STRING);
                getSendCarList(result);
            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                ToastUtils.s(act, "解析二维码失败");
            }
        }
    }


    @Override
    public void onOrderListener(OrderNumBean bean) {
        bind.sendCardView.setData(bean);
        if (bind.sendCardView.getBean() != null) {
            if (bind.sendCardView.getBean().getType() == 1) {
                bind.daohuocailiao.setVisibility(View.VISIBLE);
            }else {
                bind.daohuocailiao.setVisibility(View.GONE);
            }
        }else {
            bind.daohuocailiao.setVisibility(View.GONE);
        }
    }


    public void getSendCarList(String str) {
        try {
            JSONObject object = new JSONObject(str);
            CommonPresenter.getSendCarList(act,new DataCallBack<BaseDataBean<List<OrderNumBean>>>(act){
                @Override
                public void onResponse(BaseDataBean<List<OrderNumBean>> data) throws Exception {
                    super.onResponse(data);
                    for (OrderNumBean bean:data.getResult()){
                        if (bean.getId() == object.getInt("id")){
                            onOrderListener(bean);
                            return;
                        }
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void saveData(String list,String fullPhotoStr){
        HuoBean.OrderSendBean sendBean = new HuoBean.OrderSendBean();
        sendBean.setOrderSendDispatchingCar(bind.sendCardView.getBean());
        sendBean.setFullPhoto(fullPhotoStr);
        try {
            JSONArray array = new JSONArray(list);
            List<HuoBean.OrderMaterialTypeDetailBean> data = new ArrayList<>();
            for (int n = 0 ;n < array.length();n++){
                data.add(new Gson().fromJson(array.getString(n),HuoBean.OrderMaterialTypeDetailBean.class));
            }
            sendBean.setOrderMaterialTypeDetailList(data);
            sendBean.setSteelMillMaterialTypeStr(bind.daohuoType.getText().toString());
            if (materialTypeBean != null)
                sendBean.setSteelMillMaterialType(materialTypeBean.getId());
            huoBean.setOrderSend(sendBean);
            huoBean.setType(1);
            LocationMessageUtils.getIntent(act).saveData(huoBean);
            persenter.upStartData(act,huoBean,true);
            MainBean mainBean = new MainBean();
            mainBean.setType(1);
            mainBean.setId(huoBean.getId());
            new RxManager().post(Config.MAIN,mainBean);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCheseBack(MaterialTypeBean bean) {
        this.materialTypeBean = bean;
        bind.daohuoType.setText(bean.getName());
    }

    @Override
    public void onViewClicked() {
        if (act != null) {
            CarOrderAct.openAct(act, this);
        }
    }
}
